<template>
  <div class="app-container">
    <!--    收货信息-->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row justify="space-between" type="flex">
          <el-col :span="8"><span style="font-size: 20px;">收货信息</span></el-col>
        </el-row>
      </div>

      <!-- 使用 el-row 包裹 v-for 循环，使卡片横向排列 -->
      <el-row :gutter="20">
        <el-col
          v-for="(address, index) in addressList"
          :key="index"
          :span="6"
        >
          <!-- 单个地址卡片 -->
          <el-card class="inner-card" :style="{ width: '300px', height: '200px' }">
            <el-radio v-model="selectedAddress" :label="address">选择</el-radio>
            <div>
              <p>收货人姓名: {{ address.recipientName }}</p>
              <p>电话号码: {{ address.phoneNumber }}</p>
              <p>收货地址: {{ address.address }}</p>
            </div>
          </el-card>
        </el-col>
        <!-- 添加新地址的卡片 -->
        <el-col :span="8">
          <el-card class="inner-card" :style="{ width: '300px', height: '200px' }">
            <div>
              <el-button type="primary" @click="Add()">添加地址</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!--      添加地址信息的子页面-->
      <el-dialog :visible.sync="dialogAddFormVisible" title="添加网站信息">
        <el-form ref="form" :model="addressList">
          <el-form-item
            :label-width="formLabelWidth"
            label="收货昵称"
            prop="CategoryID"
          >
            <el-input
              v-model.number="addressList.recipientName"
              autocomplete="off"
              placeholder="请输入收货昵称"
            />
          </el-form-item>
          <!---->
          <el-form-item
            :label-width="formLabelWidth"
            label="收货地址"
            prop="CategoryID"
          >
            <el-input
              v-model.number="addressList.address"
              autocomplete="off"
              placeholder="请输入省、市、县，具体地址"
            />
          </el-form-item>
          <!---->
          <el-form-item
            :label-width="formLabelWidth"
            label="电话号码"
            prop="CategoryID"
          >
            <el-input
              v-model.number="addressList.phoneNumber"
              autocomplete="off"
              placeholder="请输入电话号码"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button icon="el-icon-circle-close" @click="handleAddCancel()">取 消</el-button>
          <el-button
            :loading="isLoading"
            icon="el-icon-circle-check"
            type="primary"
            @click="handleAdd()"
          >保 存
          </el-button>
        </div>
      </el-dialog>
    </el-card>

    <!-- 添加间距 -->
    <div style="margin-top: 20px;" />

    <!--    购物清单-->
    <el-card>
      <!--      标题以及按钮-->
      <div slot="header" class="clearfix">
        <el-row
          justify="space-between"
          type="flex"
        >
          <el-col :span="8"><span style="font-size: 20px;">购物清单</span></el-col>
        </el-row>
      </div>
      <!--      标题以及按钮-->
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        :border="false"
        element-loading-text="Loading"
        fit
        highlight-current-row
      >
        <el-table-column align="center" label="图片">
          <template slot-scope="scope">
            <img
              :src="scope.row.ProductImageURL"
              alt="Product Image"
              style="max-width: 100px; max-height: 100px;"
            >
          </template>
        </el-table-column>

        <el-table-column align="center" label="产品名">
          <template slot-scope="scope">
            {{ scope.row.ProductName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="价格" width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.ProductPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="数量" width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.TotalQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="小计" width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.TotalPrice }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <!-- 购物车下部分 -->
        <div class="cart-actions">
          <div class="info-section">
            <div class="info-row">
              <span>应付金额：<span class="highlight">￥{{ totalAmount }}</span></span>
            </div>
          </div>
          <div class="action-buttons">
            <el-button type="primary" @click="addOrder">提交订单</el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>

import { formatDate } from 'element-ui'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      background: true,
      list: null,
      listLoading: true,
      dialogFormVisible: false,
      dialogAddFormVisible: false,
      isLoading: false,
      formLabelWidth: '120px',
      // 应付总额
      totalAmount: 0,
      anyRows: [],
      form: {
        // 产品的form
        CartId: 0,
        ProductID: '',
        ProductImageURL: '',
        ProductPrice: '',
        ProductDescription: '',
        TotalPrice: new Date(),
        TotalQuantity: 0
      },
      cart: {},
      addressList: {
        userId: 0,
        addressId: 0,
        phoneNumber: '123456',
        recipientName: '示例',
        address: '示例'
      },
      productIds: [],
      selectedAddress: null
    }
  },
  created() {
    this.getAddress()
    this.getCheckout()
  },
  methods: {
    formatDate() {
      return formatDate
    },
    // 根据id获取商品
    getCheckout() {
      // 获取包含多个值的 id 数组
      const idArray = this.$route.query.id

      // 检查 idArray 是否为字符串
      const numericIdArray = typeof idArray === 'string'
        ? [parseInt(idArray, 10)] // 如果是字符串，转换为包含一个元素的数组
        : idArray.map(id => parseInt(id, 10)) // 如果是数组，转换为数字数组

      this.$store.dispatch('product/getCardById', { numericIdArray })
        .then((res) => {
          if (res.code === 0) {
            // 更新购物车列表
            this.list = res.data
            this.listLoading = false
            // 计算总数、总金额等信息
            let totalAmount = 0
            for (const item of this.list) {
              totalAmount += item.TotalPrice
            }
            // 更新本地状态
            this.totalAmount = totalAmount
          } else {
            this.$message.error(res.msg)
          }
          // 遍历每组数据，累加到 cart 中
          this.cart = this.list.map(cartItem => {
            return {
              productId: cartItem.ProductID
            }
          })
          this.cart.totalAmount = this.totalAmount
        })
    },
    getAddress() {
      this.$store.dispatch('cart/getAddress', {})
        .then((res) => {
          if (res.code === 0) {
            // 更新购物车列表
            this.addressList = res.data
            this.listLoading = false
          } else {
            this.$message.error(res.msg)
          }
        })
    },
    // 打开子页面
    Add() {
      this.dialogAddFormVisible = true
    },
    // 关闭子页面
    handleAddCancel() {
      this.dialogAddFormVisible = false
      this.form = {}
      this.$message.info('取消添加')
    },
    // 添加地址
    handleAdd() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.isLoading = true
          this.$store.dispatch('order/addAddress', {
            phoneNumber: this.addressList.phoneNumber,
            recipientName: this.addressList.recipientName,
            address: this.addressList.address
          }).then((res) => {
            console.log(res)
            if (res.code === 0) {
              this.dialogAddFormVisible = false
              this.$message.success(res.msg)
              this.form = {}
              this.getAddress()
            } else {
              this.$message.error(res.msg)
            }
          })
          this.isLoading = false
        } else {
          return false
        }
      })
    },
    // 添加到订单
    addOrder() {
      this.$store.dispatch('cart/addOrder', {
        addressId: this.selectedAddress.addressId,
        userId: this.selectedAddress.userId,
        productList: this.cart,
        totalAmount: this.totalAmount
      }
      ).then((res) => {
        if (res.code === 0) {
          this.$message.success('下单成功')
          this.getCart()
          // this.$router.push({ path: '/mall/user/order' })
          this.dialogFormVisible = false
        } else {
          this.$message.error(res.msg)
        }
      })
    }
  }
}

function time(time = +new Date()) {
  const date = new Date(time + 8 * 3600 * 1000)
  return date.toJSON().substr(0, 19).replace('T', ' ').replace(/-/g, '.')
}

time() // "2018.08.09 18:25:54"
</script>

<style scoped>
.cart-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.info-section {
  text-align: right;
  margin-right: 20px;
}

.action-buttons {
  margin-right: 20px;
}
.custom-divider {
  height: 50px; /* 设置分割线的高度为容器的高度 */
}
.highlight {
  color: red; /* 设置文字颜色为红色 */
  font-size: 1.2em; /* 设置字体大小为1.2倍（可以根据需要调整） */
}
</style>
